import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { TFood } from 'src/entities/food.entity';
import { getCurrentTime, searchKeyName } from 'src/utils/index';
import { Response } from 'src/utils/response';
import type {
  QueryParam,
  QueryResponse,
  AddParam,
  AddResponse,
  UpdateParam,
  UpdateResponse,
  DeleteParam,
  DeleteResponse,
  FoodDataInterface,
} from './food.interface';

@Injectable()
export class FoodService {
  constructor(
    @InjectRepository(TFood)
    private readonly foodRepository: Repository<TFood>,
  ) {}

  // 查询
  async findAll(keyword: QueryParam['keyword']): QueryResponse {
    try {
      // 从数据库中查询列表数据
      const result = await this.foodRepository.find();
      if (keyword) {
        const data = searchKeyName(result, 'name', keyword);
        return Response.success({ data });
      } else {
        return Response.success({ data: result });
      }
    } catch (err) {
      // 查询数据库错误
      return Response.error({ message: err, data: [] });
    }
  }

  async addFood(food: AddParam): AddResponse {
    const currentTime = getCurrentTime('YYYY-MM-DD HH:mm:ss');
    const foodInfo: FoodDataInterface = {
      ...food,
      createdAt: currentTime,
      updatedAt: currentTime,
    };
    try {
      await this.foodRepository.save(foodInfo);
      return Response.success({});
    } catch (e) {
      return Response.error({ message: e });
    }
  }

  async updateFood(food: UpdateParam): UpdateResponse {
    const currentTime = getCurrentTime('YYYY-MM-DD HH:mm:ss');
    // 这里只获取自己需要的字段，其他前端传递过来的字段舍弃
    const foodInfo: UpdateParam = {
      id: food.id,
      name: food.name,
      loveType: food.loveType,
      foodType: food.foodType,
      createdAt: food.createdAt,
      description: food.description,
      updatedAt: currentTime,
    };
    try {
      await this.foodRepository.update(food.id, foodInfo);
      return Response.success({});
    } catch (e) {
      return Response.error({ message: e });
    }
  }

  async deleteFood(id: DeleteParam['id']): DeleteResponse {
    try {
      await this.foodRepository.delete(id);
      return Response.success({});
    } catch (e) {
      return Response.error({ message: e });
    }
  }
}
